const { baseUrl } = require("./env").dev;
// 同时发送异步代码的次数
let ajaxTimes = 0;

module.exports = {
    request: function(url, method = "GET", data = {}) {
        const openId = uni.getStorageSync("openId") ? true : false;

        if (url != "/home/wxLogin") {
            if (!openId)
                return new Promise((resolve, reject) => {
                    reject("未登录不能进行操作！");
                });
        }

        // 显示加载中 效果
        uni.showLoading({
            title: "加载中",
            mask: true,
        });
        ajaxTimes++;

        let fullUrl = `${baseUrl}${url}`;
        let token = uni.getStorageSync("token") ? uni.getStorageSync("token") : "";

        return new Promise((resolve, reject) => {
            uni.request({
                url: fullUrl,
                method,
                data,
                header: {
                    "content-type": "application/json", // 默认值
                    "x-api-key": token,
                },
                success(res) {
                    if (res.data.code != 500) {
                        resolve(res.data.data);
                    } else {
                        uni.showToast({
                            title: res.data.msg,
                            icon: "none",
                        });
                        reject(res.data.message);
                    }
                },
                fail(err) {
                    console.log(err);
                    uni.showToast({
                        title: "接口请求错误",
                        icon: "none",
                    });
                    reject("接口请求错误");
                },
                complete() {
                    ajaxTimes--;
                    if (ajaxTimes === 0) {
                        //  关闭正在等待的图标
                        uni.hideLoading();
                    }
                },
            });
        });
    },
};